home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 868 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.4 KB

  1. Path: erich.triumf.ca!bennett
  2. From: bennett@erich.triumf.ca (P.Bennett)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: To malloc (new) or not to malloc?  Clarification. Please ignore previous post.
  5. Date: 9 Jan 1996 12:14 PST
  6. Organization: TRIUMF: Tri-University Meson Facility
  7. Distribution: world
  8. Message-ID: <9JAN199612145330@erich.triumf.ca>
  9. References: <4ctvk3$ort@maverick.tad.eds.com> <4cua5t$dm@maverick.tad.eds.com>
  10. NNTP-Posting-Host: ftp.triumf.ca
  11. News-Software: VAX/VMS VNEWS 1.50    
  12.  
  13. In article <4cua5t$dm@maverick.tad.eds.com>, fignet05.darrins@eds.com (Darrin Smith) writes...
  14. >Why is it that you can do something like the following:
  15. >        char *x;
  16. >        x="Some really long string with no particular meaning";
  17. >and have no problems, but can't (safely) do something like this:
  18. >        struct st1{char one[10];
  19. >                   char two[20];
  20. >                   char three[10];
  21. >                  };
  22. >        st1 *sptr;      //or struct st1 *sptr in C instead of C++
  23. >    fread(sptr,sizeof(st1),1,infile);
  24. >        
  25. >This caused a program I was trying to debug to crash.  When I allocated 
  26. >memory for sptr (I used sptr=new st1; but I suppose malloc would have done 
  27. >just as well) it worked fine.                   
  28.  
  29. If you used sptr = new st1; you were writing C++, not C.
  30. >What is going on here?  Why isn't memory set aside for st1 *sptr just as 
  31. >it is for char *x?  Before I did the new (or malloc) it seemed as though 
  32. >my program was getting written over!
  33.  
  34. char *x; and  st1 *sptr; both reserve space for a pointer, but do not set the
  35. pointers to point anywhere useful, not reserve any space for an object for the
  36. pointer to point to.
  37.  
  38. x = "some really long string...";
  39. sets the pointer x to point to the location of "some really..." which will be
  40. somewhere in your program (and not necessarily writeable).
  41.  
  42. fread(sptr, sizeof(s1), 1, infile);
  43. reads data from the file into the location pointed to by the _uninitialized_
  44. pointer sptr. This will usually have some unpleasant result  :-)
  45.  
  46.  
  47. Peter Bennett VE7CEI                | Vessels shall be deemed to be in sight
  48. Internet: bennett@triumf.ca         | of one another only when one can be
  49. Packet: ve7cei@ve7kit.#vanc.bc.ca   | observed visually from the other
  50. TRIUMF, Vancouver, B.C., Canada     |                          ColRegs 3(k)
  51. GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.